#!/usr/bin/env node
//引入fs模块
const fs = require('fs');
//解构
const join = require('path').join,
      file ='./sysFile/'+ process.argv[3] || __filename,
      err  = console.error,
      src  = process.argv[3],
      lsd = process.argv[2];
//创建空数组，用于存储输出信息
let arr = [];
//拼接路径，生成相对路径
const linkDir = join(__dirname,'sysFile');
const readDir = fs.readdirSync(linkDir);
//输出sysFile文件夹下文件信息,以json数据形式表示，并按照文件或文件夹创建时间从小到大进行排序。
if(lsd === '-list'){
   for(let i = 0;i<readDir.length;i++){
     const all = join(linkDir,readDir[i]);
     const time = new Date(fs.statSync(all).birthtimeMs);
     let year = time.getFullYear(),
         month = time.getMonth() + 1,
         day = time.getDate(),
         hour = time.getHours(),
         minute = time.getMinutes();

    const times= [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute].map(formatNumber).join(':')

      function formatNumber(n) {
          n = n.toString()
          return n[1] ? n : '0' + n;
      }
    
     const listInstr = {
       fileName:readDir[i],
       fileSize:fs.statSync(all).size, 
       createTime: times
     }

     arr[arr.length] = listInstr;
   }
   //冒泡排序
  for (let j = 0; j < arr.length - 1; j++)
  {
    for (let i = 0; i < arr.length- 1 - j; i++){
    if (fs.statSync(join(linkDir,arr[i].fileName)).birthtimeMs > fs.statSync(join(linkDir,arr[i+1].fileName)).birthtimeMs)
    {
      let temp = arr[i];
      arr[i] = arr[i + 1];
      arr[i + 1] = temp;
    }
  } 
}
//输出内容
  console.log(arr);
}

//删除
if(lsd === '-del'){
  const delName = join(linkDir,src);
try{
if(typeof(delName) === 'undefined') {
  console.error('请指定要删除的文件名或者目录名！');
  process.exit(1);
}

if(!fs.existsSync(delName)) {
  console.error('%s not exist!', src);
  process.exit(2);
}

if(fs.statSync(delName).isFile())  fs.unlinkSync(delName);

if(fs.statSync(delName).isDirectory()) deleteDir(delName);

function deleteDir(folder) {
  let files = fs.readdirSync(folder);

  for(let i=0; i<files.length; i++) {
    let file = join(folder, files[i]);

    if(fs.statSync(file).isFile()) {
      fs.unlinkSync(file);
      continue;
    }

    if(fs.statSync(file).isDirectory()) deleteDir(file);
  }

  fs.rmdirSync(folder);
}
}catch(e){}

console.log(`${src}删除成功`)

}
//打印该文件的内容,文件不存在，有提示
if(lsd === '-show'){
  if(!fs.existsSync(file)) {
      err('%s 不存在!', process.argv[3]);
        process.exit(1);
  }
try{
  console.log(fs.readFileSync(file).toString('utf8'));
} catch(err) {
  console.error(err.message);
  process.exit(1);
}
}

